import { useIntersectionObserver } from '@vueuse/core'
import { ref, onUnmounted } from 'vue'

export const useObsever = (fn: () => void) => {
  const target = ref(null)
  const { stop } = useIntersectionObserver(target, ([{ isIntersecting }]) => {
    if (isIntersecting) {
      // home.getNewGoodsList()
      stop()
      // 执行传进的函数
      fn()
    }
  })
  return { target }
}

export const useCount = () => {
  const num = ref(0)
  let timer = 0
  // 封装倒计时函数
  const start = (t = 60) => {
    // 防止多次触发
    if (num.value > 0) return
    // 传入倒计时时间
    num.value = t
    // 开启倒计时
    timer = setInterval(() => {
      num.value--
      // 判断是否为0
      if (!num.value) {
        // 关闭倒计时
        clearInterval(timer)
      }
    }, 1000)
  }

  onUnmounted(() => {
    clearInterval(timer)
  })

  return { num, start }
}
